from typing import Any
from autoapi.common.log import log
from autoapi.db.base_db import BaseDB


class MemoryCache(BaseDB):
    def __init__(self):
        self.cache = {}
        self.prefix = "autoapi"
        self.token_prefix = f"{self.prefix}:token"
        self.cookie_prefix = f"{self.prefix}:cookie"
        self.case_data_prefix = f"{self.prefix}:case_data"
        self.case_id_file_prefix = f"{self.prefix}:case_id_file"

    def init(self):
        log.info("✅ 使用 MemoryCache 作为缓存后端")

    def get(self, name: Any, *args, logging: bool = True, **kwargs) -> Any:
        return self.cache.get(name)

    def set(self, name: Any, value: Any, *args, **kwargs) -> None:
        self.cache[name] = value

    def rset(self, key: Any, value: Any, *args, **kwargs) -> None:
        self.cache[key] = value

    def delete(self, name: Any, *args, **kwargs) -> None:
        self.cache.pop(name, None)

    def delete_prefix(self, prefix: str, exclude: str | None = None) -> None:
        keys_to_delete = [
            k
            for k in self.cache
            if k.startswith(prefix) and (not exclude or not k.startswith(exclude))
        ]
        for k in keys_to_delete:
            self.cache.pop(k, None)

    def get_prefix(self, prefix: str, *args, **kwargs) -> list:
        return [v for k, v in self.cache.items() if k.startswith(prefix)]
